package cn.zglbk.network.gateway.handler.codec;
import cn.zglbk.config.GatewayServerConfig;
import cn.zglbk.network.param.GameMessageHeader;
import cn.zglbk.network.param.GameMessagePackage;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;
/**
 * @author zglbk.cn
 * @email 1030681978@qq.com
 * @date 2020/10/23 19:09
 * 编码服务器向客户端发送的数据
 */
public class EncodeHandler extends MessageToByteEncoder<GameMessagePackage> {
    private static final int GAME_MESSAGE_HEADER_LEN = 22;
    private GatewayServerConfig serverConfig;

    public EncodeHandler(GatewayServerConfig serverConfig) {
        // 注入服务端配置
        this.serverConfig = serverConfig;
    }
    // 对称加密密钥
    private String aesSecret;

    public void setAesSecret(String aesSecret) {
        this.aesSecret = aesSecret;
    }

    @Override
    protected void encode(ChannelHandlerContext ctx, GameMessagePackage msg, ByteBuf out) throws Exception {
        int messageSize = GAME_MESSAGE_HEADER_LEN;
        byte[] body = msg.getBody();
        int compress = 0;
        if (body != null) {
            // 达到压缩条件，进行压缩
            if (body.length >= serverConfig.getCompressMessageSize()) {
                //body = CompressUtils.compress(body);
                compress = 1;
            }
            if (this.aesSecret != null && msg.getHeader().getMessageId() != 1) {
                 //body = AESUtils.encode(aesSecret, body);
            }
            messageSize += body.length;
        }
        out.writeInt(messageSize);
        GameMessageHeader header = msg.getHeader();
        out.writeInt(header.getClientSeqId());
        //主动通知的时候需要这个
        out.writeInt(header.getServiceId());
        out.writeInt(header.getMessageId());
//        out.writeLong(System.currentTimeMillis());
//        out.writeInt(header.getVersion());
        out.writeByte(compress);
        out.writeInt(header.getErrorCode());
        out.writeByte(header.getMesasageType().getId());
        if (body != null) {
            out.writeBytes(body);
        }
    }
}
